﻿using System.Data;
using Dommel;
using Microsoft.AspNetCore.Mvc;
using orm.dapper.api.Entities;

namespace orm.dapper.api.Controllers
{
    /// <summary>
    /// Dommel 单表操作
    /// </summary>
    public class SingleOfDommelController(IDbConnection dbConnection) 
        : DommelBaseController(dbConnection)
    {
        [HttpPost]
        public async Task<IActionResult> Insert()
        {
            var order = new Order 
            {
                Number = DateTime.Now.ToString("yyyyMMddHHmmss"),
                CreateTime = DateTime.Now
            };

            return Ok("Id：" + await DbConnection.InsertAsync(order));
        }

        [HttpPatch]
        public async Task<IActionResult> Update(int id)
        {
            var order = await DbConnection.GetAsync<Order>(id);
            if (order != null)
            {
                order.Number = DateTime.Now.ToString("yyyyMMddHHmmss");
                order.TotalPrice = 1;
                order.CreateTime = DateTime.Now;

                return Ok(await DbConnection.UpdateAsync(order));
            }

            return Ok("Null");
        }

        [HttpDelete]
        public async Task<IActionResult> Delete(int id)
        {
            return Ok(await DbConnection
                .DeleteMultipleAsync<Order>(o => o.Id == id) > 0);
        }

        [HttpGet]
        public async Task<IActionResult> PageList(int pageIndex, int pageSize)
        {
            var rows = await DbConnection.FromAsync<Order>(sql => sql
                .Where(o => o.IsDeleted == false)
                .OrderByDescending(o => o.Id)
                .Page(pageIndex, pageSize)
                .Select());

            long total = await DbConnection.CountAsync<Order>(o => o.IsDeleted == false);
            return Ok(new { rows, total });
        }

        [HttpGet]
        public async Task<IActionResult> Detail(int id)
        {
            return Ok(await DbConnection.GetAsync<Order>(id));
        }
    }
}
